/*
 * CashPaymentView.java
 *
 * Created on August 11, 2006, 7:30 PM
 */
package com.floreantpos.ui.views.payment;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;

import com.floreantpos.main.Application;
import com.floreantpos.model.CashTransaction;
import com.floreantpos.swing.DoubleDocument;
import com.floreantpos.swing.PosButton;
import com.floreantpos.ui.dialog.POSMessageDialog;
import com.floreantpos.ui.views.PaymentView;
import com.floreantpos.ui.views.SwitchboardView;
import com.floreantpos.ui.views.order.RootView;
import java.awt.Color;
import java.text.NumberFormat;
import java.util.Locale;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 *
 * @author MShahriar
 */
public class CashPaymentView extends PaymentView {

  public final static String VIEW_NAME = "CASHPAYMENT_VIEW";
  private int guestID;
  private Boolean giftCertStatus;
  private Double gratuityAmount;
  private Double tenderedAmount;
  private NumberFormat numberFormat = NumberFormat.getInstance(new Locale("pt", "BR"));
  private String taxId;

  public CashPaymentView(String inputTaxId) {
    initComponents();
    guestID = 0;
    giftCertStatus = true;
    taxId = inputTaxId;
    tfAmountTendered.setText("0");
    tfGratuityAmount.setText("0");
    tfAmountTendered.setFocusable(giftCertStatus);
    tfGratuityAmount.setFocusable(giftCertStatus);
    btnExactChange.setEnabled(giftCertStatus);
    btnNextAmount.setEnabled(giftCertStatus);

    DoubleDocument gratuityDocument = new DoubleDocument();
    gratuityDocument.addDocumentListener(new DocumentListener() {
      void updatePayAmount() {
        double cashAmount = 0;
        double gratuity = 0;

        try {
          gratuity = numberFormat.parse(tfGratuityAmount.getText()).doubleValue();
        } catch (Exception x) {

        }
        cashAmount = getDueAmount();
        tfAmountTendered.setText(Application.formatNumber(cashAmount + gratuity));
      }

      public void insertUpdate(DocumentEvent e) {
        updatePayAmount();
      }

      public void removeUpdate(DocumentEvent e) {
        updatePayAmount();
      }

      public void changedUpdate(DocumentEvent e) {
        updatePayAmount();
      }

    });

  }

  public CashPaymentView(Boolean giftCertEnabled, int registeredGuest, String inputTaxId) {
    initComponents();
    guestID = registeredGuest;
    taxId = inputTaxId;
    giftCertStatus = giftCertEnabled;
    tfAmountTendered.setText("0");
    tfGratuityAmount.setText("0");
    tfAmountTendered.setFocusable(giftCertStatus);
    tfGratuityAmount.setFocusable(giftCertStatus);
    btnExactChange.setEnabled(giftCertStatus);
    btnNextAmount.setEnabled(giftCertStatus);

    DoubleDocument gratuityDocument = new DoubleDocument();
    gratuityDocument.addDocumentListener(new DocumentListener() {
      void updatePayAmount() {
        double cashAmount = 0;
        double gratuity = 0;

        try {
          gratuity = numberFormat.parse(tfGratuityAmount.getText()).doubleValue();
        } catch (Exception x) {

        }
        cashAmount = getDueAmount();
        tfAmountTendered.setText(Application.formatNumber(cashAmount + gratuity));
      }

      public void insertUpdate(DocumentEvent e) {
        updatePayAmount();
      }

      public void removeUpdate(DocumentEvent e) {
        updatePayAmount();
      }

      public void changedUpdate(DocumentEvent e) {
        updatePayAmount();
      }

    });

  }

  private void initComponents() {
    jPanel1 = new com.floreantpos.swing.TransparentPanel();
    jLabel1 = new javax.swing.JLabel();
    tfGratuityAmount = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    tfAmountTendered = new javax.swing.JTextField();
    calcButtonPanel = new com.floreantpos.swing.TransparentPanel();
    tfNullAmount = new javax.swing.JTextField();
    posButton1 = new com.floreantpos.swing.PosButton();
    posButton2 = new com.floreantpos.swing.PosButton();
    posButton3 = new com.floreantpos.swing.PosButton();
    posButton4 = new com.floreantpos.swing.PosButton();
    posButton5 = new com.floreantpos.swing.PosButton();
    posButton6 = new com.floreantpos.swing.PosButton();
    posButton9 = new com.floreantpos.swing.PosButton();
    posButton8 = new com.floreantpos.swing.PosButton();
    posButton7 = new com.floreantpos.swing.PosButton();
    posButton11 = new com.floreantpos.swing.PosButton();
    posButton10 = new com.floreantpos.swing.PosButton();
    posButton12 = new com.floreantpos.swing.PosButton();
    jPanel3 = new com.floreantpos.swing.TransparentPanel();
    jPanel4 = new com.floreantpos.swing.TransparentPanel();
    btnChangePayment = new com.floreantpos.swing.PosButton();
    btnExactChange = new com.floreantpos.swing.PosButton();
    btnNextAmount = new com.floreantpos.swing.PosButton();
    jPanel5 = new com.floreantpos.swing.TransparentPanel();
    btnFinish = new com.floreantpos.swing.PosButton();
    btnCancel = new com.floreantpos.swing.PosButton();

    setBorder(javax.swing.BorderFactory.createTitledBorder(null, com.floreantpos.POSConstants.CASH_TRANSACTION, javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));
    setLayout(new java.awt.BorderLayout(5, 5));

    jPanel1.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(1, 5, 1, 5), javax.swing.BorderFactory.createTitledBorder("")));
    jPanel1.setPreferredSize(new java.awt.Dimension(98, 130));
    jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18));
    jLabel1.setForeground(new java.awt.Color(204, 102, 0));
    jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
    jLabel1.setText(com.floreantpos.POSConstants.TIP_VALUE);

    tfGratuityAmount.setEditable(false);
    tfGratuityAmount.setFont(new java.awt.Font("Tahoma", 1, 24));
    tfGratuityAmount.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
    tfGratuityAmount.setText("0");
    tfGratuityAmount.setPreferredSize(new java.awt.Dimension(21, 40));
    tfGratuityAmount.setBackground(Color.WHITE);

    jLabel2.setFont(new java.awt.Font("Tahoma", 1, 18));
    jLabel2.setForeground(new java.awt.Color(204, 102, 0));
    jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
    jLabel2.setText(com.floreantpos.POSConstants.AMOUNT);

    tfAmountTendered.setEditable(false);
    tfAmountTendered.setFont(new java.awt.Font("Tahoma", 1, 24));
    tfAmountTendered.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
    tfAmountTendered.setText("0");
    tfAmountTendered.setPreferredSize(new java.awt.Dimension(21, 40));
    tfAmountTendered.setBackground(Color.WHITE);

    tfNullAmount.setText("0");

    org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 298, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(tfGratuityAmount, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 298, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 298, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(tfAmountTendered, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 298, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(20, 20, 20))
    );
    jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                    .add(jLabel1)
                    .add(tfGratuityAmount, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 29, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jLabel2)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(tfAmountTendered, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 29, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    add(jPanel1, java.awt.BorderLayout.NORTH);

    calcButtonPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 0, 5));
    calcButtonPanel.setLayout(new java.awt.GridLayout(0, 3, 5, 5));

    posButton1.setAction(calAction);
    posButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/7_32.png")));
    posButton1.setActionCommand("7");
    posButton1.setFocusable(false);
    calcButtonPanel.add(posButton1);

    posButton2.setAction(calAction);
    posButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/8_32.png")));
    posButton2.setActionCommand("8");
    posButton2.setFocusable(false);
    calcButtonPanel.add(posButton2);

    posButton3.setAction(calAction);
    posButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/9_32.png")));
    posButton3.setActionCommand("9");
    posButton3.setFocusable(false);
    calcButtonPanel.add(posButton3);

    posButton4.setAction(calAction);
    posButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/4_32.png")));
    posButton4.setActionCommand("4");
    posButton4.setFocusable(false);
    calcButtonPanel.add(posButton4);

    posButton5.setAction(calAction);
    posButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/5_32.png")));
    posButton5.setActionCommand("5");
    posButton5.setFocusable(false);
    calcButtonPanel.add(posButton5);

    posButton6.setAction(calAction);
    posButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/6_32.png")));
    posButton6.setActionCommand("6");
    posButton6.setFocusable(false);
    calcButtonPanel.add(posButton6);

    posButton9.setAction(calAction);
    posButton9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/1_32.png")));
    posButton9.setActionCommand("1");
    posButton9.setFocusable(false);
    calcButtonPanel.add(posButton9);

    posButton8.setAction(calAction);
    posButton8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/2_32.png")));
    posButton8.setActionCommand("2");
    posButton8.setFocusable(false);
    calcButtonPanel.add(posButton8);

    posButton7.setAction(calAction);
    posButton7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/3_32.png")));
    posButton7.setActionCommand("3");
    posButton7.setFocusable(false);
    calcButtonPanel.add(posButton7);

    posButton11.setAction(calAction);
    posButton11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/0_32.png")));
    posButton11.setActionCommand("0");
    posButton11.setFocusable(false);
    calcButtonPanel.add(posButton11);

    posButton10.setAction(calAction);
    posButton10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/dot_32.png")));
    posButton10.setActionCommand(".");
    posButton10.setFocusable(false);
    calcButtonPanel.add(posButton10);

    posButton12.setAction(calAction);
    posButton12.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/clear_32.png")));
    posButton12.setActionCommand(com.floreantpos.POSConstants.CLEAR);
    posButton12.setFocusable(false);
    calcButtonPanel.add(posButton12);

    add(calcButtonPanel, java.awt.BorderLayout.CENTER);

    jPanel3.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 3, 1, 3));
    jPanel3.setPreferredSize(new java.awt.Dimension(100, 130));
    jPanel3.setLayout(new java.awt.GridLayout(2, 0, 2, 5));

    jPanel4.setLayout(new java.awt.GridLayout(1, 0, 5, 5));

    btnChangePayment.setText("<html><body><p align='center'>Alterar Forma Pagamento</p></body></html>");
    btnChangePayment.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        btnChangePaymentActionPerformed(evt);
      }
    });

    jPanel4.add(btnChangePayment);

    btnExactChange.setText(com.floreantpos.POSConstants.EXACT_VALUE);
    btnExactChange.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        btnExactChangeActionPerformed(evt);
      }
    });

    jPanel4.add(btnExactChange);

    btnNextAmount.setText(com.floreantpos.POSConstants.NEXT_VALUE);
    btnNextAmount.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        btnNextAmountActionPerformed(evt);
      }
    });

    jPanel4.add(btnNextAmount);

    jPanel3.add(jPanel4);

    jPanel5.setLayout(new java.awt.GridLayout(1, 0, 5, 5));

    btnFinish.setText(com.floreantpos.POSConstants.CAPITAL_SETTLE);
    btnFinish.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        doFinish(evt);
      }
    });

    jPanel5.add(btnFinish);

    btnCancel.setText(com.floreantpos.POSConstants.CAPITAL_VOID);
    btnCancel.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        btnCancelActionPerformed(evt);
      }
    });

    jPanel5.add(btnCancel);

    jPanel3.add(jPanel5);

    add(jPanel3, java.awt.BorderLayout.SOUTH);

  }

  private void btnChangePaymentActionPerformed(java.awt.event.ActionEvent evt) {
    if (giftCertStatus) {
      changePaymentMethod(taxId);
    } else {
      changePaymentMethod(giftCertStatus, guestID, taxId);
    }
  }

  private Boolean getAmounts() {
    try {
      gratuityAmount = numberFormat.parse(tfGratuityAmount.getText()).doubleValue();
    } catch (Exception e) {
      POSMessageDialog.showError(com.floreantpos.POSConstants.INCORRECT_TIP_VALUE);
      return false;
    }

    try {
      tenderedAmount = numberFormat.parse(tfAmountTendered.getText()).doubleValue();
    } catch (Exception e) {
      POSMessageDialog.showError(com.floreantpos.POSConstants.INVALID_AMOUNT);
      return false;
    }

    if (tenderedAmount == 0 || tenderedAmount - gratuityAmount < 0) {
      POSMessageDialog.showError(com.floreantpos.POSConstants.INSUFFICIENT_VALUE);
      return false;
    }

    return true;
  }

  private void doFinish(java.awt.event.ActionEvent evt) {
    
    if(!isTicketDiscountOk()) {
      POSMessageDialog.showError("Valor do Desconto deve ser menor que o Valor do Pedido");
      return;
    }    

    if (getAmounts()) {
      settleTickets(tenderedAmount, gratuityAmount, new CashTransaction(), null, "0", taxId);      
    }
  }

  private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {
    RootView.getInstance().showView(SwitchboardView.VIEW_NAME);
  }

  private void btnExactChangeActionPerformed(java.awt.event.ActionEvent evt) {
    if (getAmounts()) {
      settleTickets(tenderedAmount, gratuityAmount, new CashTransaction(), null, "0", taxId);
    }
  }

  private void btnNextAmountActionPerformed(java.awt.event.ActionEvent evt) {
    if (getAmounts()) {
      settleTickets(Math.ceil(tenderedAmount), gratuityAmount, new CashTransaction(), null, "0", taxId);
    }
  }

  private com.floreantpos.swing.PosButton btnCancel;
  private com.floreantpos.swing.PosButton btnChangePayment;
  private com.floreantpos.swing.PosButton btnExactChange;
  private com.floreantpos.swing.PosButton btnFinish;
  private com.floreantpos.swing.PosButton btnNextAmount;
  private com.floreantpos.swing.TransparentPanel calcButtonPanel;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private com.floreantpos.swing.TransparentPanel jPanel1;
  private com.floreantpos.swing.TransparentPanel jPanel3;
  private com.floreantpos.swing.TransparentPanel jPanel4;
  private com.floreantpos.swing.TransparentPanel jPanel5;
  private com.floreantpos.swing.PosButton posButton1;
  private com.floreantpos.swing.PosButton posButton10;
  private com.floreantpos.swing.PosButton posButton11;
  private com.floreantpos.swing.PosButton posButton12;
  private com.floreantpos.swing.PosButton posButton2;
  private com.floreantpos.swing.PosButton posButton3;
  private com.floreantpos.swing.PosButton posButton4;
  private com.floreantpos.swing.PosButton posButton5;
  private com.floreantpos.swing.PosButton posButton6;
  private com.floreantpos.swing.PosButton posButton7;
  private com.floreantpos.swing.PosButton posButton8;
  private com.floreantpos.swing.PosButton posButton9;
  private javax.swing.JTextField tfAmountTendered;
  private javax.swing.JTextField tfGratuityAmount;
  private javax.swing.JTextField tfNullAmount;

  public void resetView() {
    tfAmountTendered.setText("0");
  }

  Dimension preferredSize = new Dimension(330, 100);

  public Dimension getPreferredSize() {
    return preferredSize;
  }

  private JTextField getFocusedTextField() {
    if (!tfAmountTendered.isFocusable()) {
      return tfNullAmount;
    }
    if (tfGratuityAmount.hasFocus()) {
      return tfGratuityAmount;
    }
    if (tfAmountTendered.hasFocus()) {
      return tfAmountTendered;
    }
    return tfAmountTendered;
  }

  Action calAction = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
      JTextField tf = getFocusedTextField();
      PosButton button = (PosButton) e.getSource();
      String s = button.getActionCommand();
      if (s.equals(com.floreantpos.POSConstants.CLEAR)) {
        tf.setText("0");
      } else if (s.equals(".")) {
        if (tf.getText().indexOf(',') < 0) {
          tf.setText(tf.getText() + ",");
        }
      } else {
        String string = tf.getText();
        int index = string.indexOf(',');
        if (index < 0) {
          double value = 0;
          try {
            value = numberFormat.parse(string).doubleValue();
          } catch (Exception x) {
            Toolkit.getDefaultToolkit().beep();
          }
          if (value == 0) {
            tf.setText(s);
          } else {
            tf.setText(Application.formatTextAsNumber(string + s));
          }
        } else {
          tf.setText(Application.formatTextAsNumber(string + s));
        }
      }
      if (tf == tfGratuityAmount) {
        double gAmount = 0;
        double amount = getDueAmount();
        try {
          gAmount = numberFormat.parse(tfGratuityAmount.getText()).doubleValue();
        } catch (Exception x) {
          return;
        }
        tfAmountTendered.setText(Application.formatNumber(amount + gAmount));
      }
    }
  };

  @Override
  public void updateView() {
    tfAmountTendered.setText(Application.formatNumber(getDueAmount() + getTotalGratuity()));
    tfGratuityAmount.setText(Application.formatNumber(getTotalGratuity()));
  }
}
